package controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import domin.Actor;
import lombok.extern.slf4j.Slf4j;
import service.ActorService;

import util.Condition;
import util.Pagination;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/actor.ctl")
@Slf4j
public class ActorController extends HttpServlet {
    private ActorService actorService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        String id_str = request.getParameter("id");
        try{
            if(id_str!=null)
            {
                int id = Integer.parseInt(id_str);
                responseActor(id, response);
                log.trace("查找id" + id);
            }
            else {
            this.responsesActors(response,null,null);
            }
        }catch (SQLException e){
            System.out.println(e.getMessage());
        }
    }
    private void responsesActors(HttpServletResponse response, Collection<Condition> condition, Pagination pagination)
            throws ServletException, IOException,SQLException{
        Collection<Actor> actors = actorService.getInstance().findAll(condition,pagination);
        String actors_json = JSON.toJSONString(actors, SerializerFeature.DisableCircularReferenceDetect);
        response.getWriter().println(actors_json);
    }
    private void responseActor(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        Actor actor = ActorService.getInstance().find(id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",actor);
        response.getWriter().println(jsonObject);
    }
}
